package com.api.volunteer.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.api.volunteer.dto.AccessTokenDTO;
import com.api.volunteer.model.AccessToken;
import com.api.volunteer.model.VolunteerRecord;
import com.api.volunteer.repository.AccessTokenRepository;
import com.api.volunteer.repository.VolunteerRecordRepository;
import com.api.volunteer.service.SubcribeMessageService;
import com.api.volunteer.service.VolunteerRecordService;
import com.api.volunteer.util.Result;
import com.google.gson.JsonObject;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author 邹宇杰
 * @email 2901570623@qq.com
 * @date 2022/4/1 12:29
 */
@Service("volunteerRecordService")
@Transactional(rollbackOn = Exception.class)
public class VolunteerRecordServiceImpl implements VolunteerRecordService {

    @Autowired
    VolunteerRecordRepository volunteerRecordRepository;

    @Autowired
    AccessTokenRepository accessTokenRepository;

    private String urlTemplate = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    private String sendTemplate = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s";

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    SubcribeMessageService subcribeMessageService;

    @Override
    public Result sendMessage(String volunteerId, String templateId) {
        Result result = new Result();
        List<VolunteerRecord> volunteerRecords = volunteerRecordRepository.findVolunteerRecordByVolunteerId(volunteerId);

        if(volunteerRecords.isEmpty()){
            result.put("code", 210).put("message", "没有任何人订阅该志愿活动");
        }else{
            subcribeMessageService.sendVolunteerMessage(volunteerRecords);

            result.put("code", 200).put("message", "消息推送成功");

        }
        return result;
    }
}
